from peewee import *
from models.BaseModel import BaseModel
from entry.Entrys import Page
from util.Model2Dict import m2d
""" 系统所有的菜单 """
class Menu(BaseModel):
    mId = BigIntegerField(db_column='m_id',primary_key=True)
    parent = BigIntegerField(db_column='parent')
    key = CharField(db_column='key')
    name = CharField(db_column='name')
    icon = CharField(db_column='icon')
    iconType = CharField(db_column='icon_type')
    path = CharField(db_column='path')
    component = CharField(db_column='component')
    createTime = DateTimeField(db_column='create_time')
    status = CharField(db_column='status')
    faceShow = CharField(db_column='face_show')
    sort = IntegerField()

    # 设置模型对应的数据库表名
    class Meta:
        table_name = 'sys_menu'

""" 系统接口表 """
class SysHandle(BaseModel):
    hId = BigIntegerField(db_column='h_id',primary_key=True)
    name = CharField(db_column='name')
    key = CharField(db_column='key')
    path = CharField(db_column='path')
    method = CharField(db_column='method')
    status = CharField(db_column='status')
    log = CharField()
    type = CharField()

    class Meta:
        table_name = 'sys_handle'

# 菜单按钮表
class MenuHandle(BaseModel):
    hId = BigIntegerField(db_column='h_id')
    mId = IntegerField(db_column='m_id')
    status = CharField(db_column='status')
    show = CharField(db_column='show')
    tag = CharField(primary_key=True)
    icon = CharField()
    type = CharField()
    style = CharField()
    iconType = CharField(db_column = 'icon_type')
    name = CharField(db_column='name')
    class Meta:
        table_name = 'sys_menu_handle'
        
""" 获取所有的菜单 """
def getAllMenu(page:Page=Page()):
    r = Menu.select().paginate(page.num,page.size).dicts()
    page.count = Menu.select().count()
    page.rows = m2d(r)
    return page.__dict__

def getAllMenus():
    r = Menu.select().dicts()
    return m2d(r)

""" 获取所有的名 """
def getAllMenuName(page:Page=Page()):
    r = Menu.select(Menu.mId,Menu.name).paginate(page.num,page.size).dicts()
    page.count = Menu.select().count()
    page.rows = m2d(r)
    return page.__dict__

""" 更新某个菜单的属性 """
def updateMenu(id:int,k):
    return Menu.update(k).where(Menu.mId == id).execute() > 0

# 根据获取 id 在ids 的所有菜单
def getMenusInMIds(mids:list[int]):
    ms = Menu.select().where(Menu.mId.in_(mids)).dicts()
    return m2d(ms)

# 获取所有parent在id集合里的菜单
def getMenusInPids(mids:list[int]):
    return m2d(Menu.select().where(Menu.parent.in_(mids)).dicts())

# 查询所选菜单是否拥有子菜单
def MenuHasChild(mids:list[int]):
    return Menu.select().where(Menu.parent.in_(mids)).count()>0

# 根据菜单id 删除菜单
def delMenuInMId(mid:list[int]):
    return Menu.delete().where(Menu.mId.in_(mid)).execute()>0

# 根据父菜单删除菜单
def delMenuInPid(id:list[int]):
    return Menu.delete().where(Menu.parent.in_(id)).execute()>0

# 添加菜单
def addMenu(k) -> int:
    return Menu.insert(k).execute()

# 查询菜单是否存在
def hasMenu(mid) -> bool:
    return Menu.select(Menu.mId).where(Menu.mId == mid).count()>0
# 查询接口是否存在
def hasHandle(hid) -> bool:
    return SysHandle.select(SysHandle.hId).where(SysHandle.hId == hid).count()>0
# 根据路径已经接口方法查询菜单是否存在
def hasHandleByPathMethod(path:str,method:str):
    return SysHandle.select(SysHandle.hId).where(SysHandle.path == path,SysHandle.method==method).count()>0
# 查询是菜单是否存在且可用
def hasCanUseHandleByPathMethod(path:str,method:str):
    return SysHandle.select(SysHandle.hId).where(SysHandle.path == path,SysHandle.method==method,SysHandle.status == '1').count()>0
""" 获取系统所有的接口 """
def getAllHandle(page:Page = Page(),cdn:dict = dict(),hids:list[int] = None):
    query = SysHandle.select()
    if hids!=None:
        query = query.where(SysHandle.hId.in_(hids))
    if cdn.get('path'):
        query = query.where(SysHandle.path.startswith(cdn.get('path')))
    if cdn.get('method'):
        query = query.where(SysHandle.method == cdn.get('method'))
    if cdn.get('key'):
        query = query.where(SysHandle.key == cdn.get('key'))
    if cdn.get('type'):
        query = query.where(SysHandle.type == cdn.get('type'))
    if cdn.get('status'):
        query = query.where(SysHandle.status == cdn.get('status'))
    if cdn.get('name'):
        query = query.where(SysHandle.name.contains(cdn.get('name')))
    r = query.paginate(page.num,page.size).dicts()
    page.count = query.count()
    page.rows = m2d(r)
    return page.__dict__

""" 获取系统所有的接口名 """
def getAllHandleName(page:Page = Page(),cdn:dict = dict()):
    query = SysHandle.select(SysHandle.name,SysHandle.hId)
    if cdn.get('path'):
        query = query.where(SysHandle.path.startswith(cdn.get('path')))
    if cdn.get('method'):
        query = query.where(SysHandle.method == cdn.get('method'))
    if cdn.get('key'):
        query = query.where(SysHandle.key == cdn.get('key'))
    if cdn.get('type'):
        query = query.where(SysHandle.type == cdn.get('type'))
    if cdn.get('status'):
        query = query.where(SysHandle.status == cdn.get('status'))
    if cdn.get('name'):
        query = query.where(SysHandle.name.contains(cdn.get('name')))
    r = query.paginate(page.num,page.size).dicts()
    page.count = query.count()
    page.rows = m2d(r)
    return page.__dict__

    
# 更新接口数据
def updateHandle(id:int,k):
    return SysHandle.update(k).where(SysHandle.hId.in_(id)).execute() > 0

# 根据id 查询接口
def getHandlesInId(ids:list):
    r = SysHandle.select().where(SysHandle.hId.in_(ids)).dicts()
    return m2d(r)
# 更具类型查询相应类型下的所有 接口id
def getHandleNameByType(type:str):
    r = SysHandle.select(SysHandle.hId,SysHandle.name).where(SysHandle.type == type).dicts()
    return m2d(r)

# 根据系统接口列表删除系统接口
def delHandleInId(id:list[int]):
    return SysHandle.delete().where(SysHandle.hId.in_(id)).execute()>0

# 添加系统接口
def addHandle(k) -> int:
    return SysHandle.insert(k).execute()     

# 根据接口路径以及接口方法获取系统接口
def getHandleByPathAndMethod(path:str,method:str):
    r = SysHandle.select().where(SysHandle.path == path,SysHandle.method == method).dicts()
    if(len(r)>0):
        return m2d(r)[0]
    return None

# 根据接口路径获取能够使用的系统接口id
def HandleCanUseIdByPath(path:str):
    r = SysHandle.select(SysHandle.hId).where(SysHandle.path == path,SysHandle.status == '1').dicts()
    if(len(r)>0):
        return m2d(r)[0]["hId"]
    return None

# 根据 菜单id 查询 菜单上所有的按钮id
def getAllMenuHandleTags(mid:list[int])->list[str]:
    r = MenuHandle.select(MenuHandle.tag).where(MenuHandle.mId.in_(mid)).dicts()
    return [item['tag'] for item in m2d(r)]
    
# 根据菜单获取所有的菜单按钮
def getAllMenuHandleInMids(mids:list[int]):
    r = MenuHandle.select().where(MenuHandle.mId.in_(mids)).dicts()
    return m2d(r)

# 删除所有菜单按钮和系统接口的映射关系
def delMenuHandleInHid(hid:list[int]):
    return MenuHandle.delete().where(MenuHandle.hId.in_(hid)).execute()

""" 删除某个菜单的所有按钮 """
def delMenuHandleInMid(mid:list[int]):
    count = MenuHandle.delete().where(MenuHandle.mId.in_(mid)).execute()
    if count>0:
        return True
    return False

""" 查询菜单是否拥有某(接口)按钮权限 """
def hasMenuHandle(tag:str)->bool:
    if MenuHandle.select(MenuHandle.hId).where(MenuHandle.tag == tag).count()>0:
        return True
    return False

""" 为用户添加菜单 """
def addMenuHandle(mhs:list[dict]):
    MenuHandle.insert_many(mhs).execute()
    return True

""" 根据path获取SysHandle表的handleName属性用于日志"""
def getHandleByPath(path):
    r = m2d(SysHandle.select().where(SysHandle.path == path).dicts())
    if(len(r)>0):
        return r[0]
    return None
